package com.huangd.platform.modules.sys.controller;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.huangd.platform.modules.sys.entity.TblUserEntity;
import com.huangd.platform.modules.sys.entity.to.SetUserTagTo;
import com.huangd.platform.modules.sys.form.PasswordForm;
import com.huangd.platform.modules.sys.service.TblRoleService;
import com.huangd.platform.modules.sys.service.TblUserRoleService;
import com.huangd.platform.modules.sys.service.TblUserService;
import com.huangd.platform.common.annotation.SysLog;
import com.huangd.platform.common.utils.Constant;
import com.huangd.platform.common.utils.PageUtils;
import com.huangd.platform.common.utils.R;
import com.huangd.platform.common.validator.Assert;
import com.huangd.platform.common.validator.ValidatorUtils;
import com.huangd.platform.common.validator.group.AddGroup;
import com.huangd.platform.common.validator.group.UpdateGroup;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 
 *
 * @author huangd
 * @email
 * @date 2022-03-29 10:51:03
 */
@RestController
@Api(tags={"用户相关"})
@RequestMapping("sys/user")
public class SysUserController extends AbstractController {
    @Resource
    private TblUserService sysUserService;

    @Resource
    private TblUserRoleService userRoleService;

    @Resource
    private TblRoleService roleService;



    /**
     * 所有用户列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "所有用户列表")
    @RequiresPermissions("sys:user:list")
    public R list(){
        //只有超级管理员，才能查看所有管理员列表
        List<Integer> list = userRoleService.queryRoleIdList(getUserId().longValue());
        if(!list.contains(Constant.SUPER_ADMIN)){
            return R.error("非管理员不能查看用户列表");
        }
        Map<String, Object> map = new HashMap<>();
        PageUtils page = sysUserService.queryPage(map);

        return R.ok(page);
    }

    /**
     * 获取登录的用户信息
     */
    @GetMapping("/info")
    public R info(){
        return info(new Long(getUserId()));
    }

    /**
     * 修改登录用户密码
     */
    @SysLog("修改密码")
    @ApiOperation(value = "修改密码")
    @PostMapping("/password")
    public R password(@RequestBody PasswordForm form){
        Assert.isBlank(form.getNewPassword(), "新密码不为能空");

        //MD5
        String password = SecureUtil.md5(form.getPassword());
        //MD5
        String newPassword = SecureUtil.md5(form.getNewPassword());

        //更新密码
        boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
        if(!flag){
            return R.error("原密码不正确");
        }

        return R.ok();
    }

    /**
     * 用户信息
     */
    @GetMapping("/info/{userId}")
    @ApiOperation(value = "用户信息")
    @RequiresPermissions("sys:user:info")
    public R info(@PathVariable("userId") Long userId){
        return R.ok(sysUserService.getByUid(userId));
    }

    /**
     * 保存用户
     */
    @SysLog("保存用户")
    @PostMapping("/save")
    @ApiOperation(value = "保存用户")
    @RequiresPermissions("sys:user:save")
    public R save(@RequestBody TblUserEntity user){
        ValidatorUtils.validateEntity(user, AddGroup.class);

        sysUserService.saveUser(user);

        return R.ok();
    }

    /**
     * 修改用户
     */
    @SysLog("修改用户")
    @PostMapping("/update")
    @ApiOperation(value = "修改用户")
    @RequiresPermissions("sys:user:update")
    public R update(@RequestBody TblUserEntity user){
        ValidatorUtils.validateEntity(user, UpdateGroup.class);

        sysUserService.update(user);

        return R.ok();
    }

    /**
     * 删除用户
     */
    @SysLog("删除用户")
    @PostMapping("/delete")
    @ApiOperation(value = "删除用户")
    @RequiresPermissions("sys:user:delete")
    public R delete(@RequestBody Long[] userIds){
        if(ArrayUtils.contains(userIds, 1L)){
            return R.error("系统管理员不能删除");
        }

        if(ArrayUtils.contains(userIds, getUserId())){
            return R.error("当前用户不能删除");
        }

        sysUserService.deleteBatch(userIds);

        return R.ok();
    }
    /**
     * 设置常用功能id
     */
    @PostMapping("/updateTag")
    @ApiOperation(value = "设置常用功能id")
    //@RequiresPermissions("sys:user:updateTag")
    public R updateTag(@RequestBody SetUserTagTo userTagTo){
        return sysUserService.updateTag(userTagTo);
    }

    /**
     * 导出数据测试
     */
    @PostMapping("/outputWeb")
    @ApiOperation(value = "导出数据测试")
    public void outputWeb(HttpServletResponse response) throws IOException {
        String fileName = new String("导出excel.xlsx".getBytes(), StandardCharsets.ISO_8859_1);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setCharacterEncoding("utf8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName );
        ServletOutputStream outputStream = response.getOutputStream();
        EasyExcel.write(outputStream, Student.class)
                .sheet("sheet1").doWrite(getData());
    }

    /**
     * 准备数据
     * @return
     */
    private List<Student> getData(){
        List<Student> list = new ArrayList<Student>();
        for(int i = 0 ; i < 10 ; i ++){
            Student student = new Student();
            student.setId("stu" + i);
            student.setName("wang" + i);
            student.setAge( 18 + i );
            student.setTelephone("1361234" + i);
            student.setEmail("wang" + i + "@czxy.com");
            student.setBrithday(new Date());
            list.add(student);
        }
        return list;
    }

    @Data
    public class Student {
        @ExcelProperty("编号")
        private String id;

        @ExcelProperty("姓名")
        private String name;

        @ExcelProperty("年龄")
        private Integer age;

        @ExcelProperty("电话")
        private String telephone;

        @ExcelProperty("邮箱")
        private String email;

        @ExcelProperty("生日")
        private Date brithday;
    }
}
